import { openAppClient, showLoading, hideLoading, webprintReport } from '@/utils/common'
import auditRequest from '@/api/subcontractApi/audit.js'
import { getRmbRate } from '@/api/equip/common.js'
// 审核相关操作
async function  exas  (arg, vueObject, requestFn, printData) {
    const _this = vueObject
    if (arg === 'audit') {
        showLoading()
        _this.errorList = []
        Promise.all(requestFn())
            .then(() => {
                _this.$store.commit('contract/setMaterialList', [])
                hideLoading()
                _this.auditParams.isPass = true
                _this.setAuditParams(_this.auditParams)
                // 客户端弹窗弹出本地页面
                openAppClient('/exaDialog', '填写审核意见', () => {
                    const auditParams = JSON.parse(localStorage.vuex).auditParams
                    showLoading()
                    auditRequest.audit(auditParams).then(() => {
                        hideLoading()
                        _this.clientPop('suc', '审核成功', _this.handleClose)
                    }).catch(()=>{
                        hideLoading()
                    })
                }, null, null, null, 'small')
            })
            .catch(err => {
                console.log('errMsg：', err)
                _this.scorllError()
            })
            .finally(() => {
                hideLoading()
            })
    } else if (arg === 'undoAudit') {
        _this.clientPop('info', _this.undoAudit, ()=>{
            showLoading()
            auditRequest.undoAudit(_this.auditParams).then(() => {
                hideLoading()
                _this.clientPop('suc', '撤回成功', _this.handleClose)
            }).finally(() => {
                hideLoading()
            })
        })
    } else if (arg === 'submitCommit') {
        _this.submitCommit()  //保存并提交
    } else if (arg === 'submit') {
        _this.saveAll()   //保存
    } else if (arg === 'nullify') {
        _this.setAuditParams(_this.nullifyParams)
        // 客户端弹窗弹出本地页面
        openAppClient('/nullifyDialog', '单据作废原因', () => {
            const auditParams = JSON.parse(localStorage.vuex).auditParams
            showLoading()
            auditRequest.nullify(auditParams).then(() => {
                hideLoading()
                _this.clientPop('suc', '作废成功', _this.handleClose, null, null, null, 'small')
            }).finally(() => {
                hideLoading()
            })
        })
    } else if (arg === 'deleteData') {
        _this.deleteBaseInfo()
    }
    else if (arg === 'print') {
        const data = await printData()
        //审核历史
        const auditParams = {
            billId: _this.$route.query.billid || _this.$route.query.tenderId,
            billType: parseInt(_this.auditParams.billType),
            freeNextUnitIndex: 0,
            freeNextUser: '',
            isPass: true,
            isShareInAudit: true,
            opinion: ''
        }
        const historyTable  = await auditRequest.getAuditHistory(auditParams)
        const historyList = {
            'tableTitle': '审核历史',
            'tableContent': {
                '审核级次': 'unitName',
                '审核人': 'assignUser',
                '审核人岗位': 'userTitle',
                '通知时间': 'notifyTime',
                '审核时间': 'completeTime',
                '审核意见': 'opinion',
            },
            'tableData': historyTable, //表格数据
        }
        data.tables.push(historyList)
        webprintReport(data)
    }
    else if (arg === 'financialAudit') {
        const auditParams = {
            'billId': _this.$route.query.billid || _this.$route.query.tenderId,
            'billType': parseInt(_this.auditParams.billType),
            'cwAuditState': 1,
            'freeNextUnitIndex': 0,
            'freeNextUser': '',
            'isPass': true,
            'isShareInAudit': true,
            'opinion': '3432',
            'orgId': 'ad551eff9d03-8efe-2148-9ed8-64781e1e',
            'orgName': '',
            'returnEmpId': 'abb5184d43ca-960c-b640-c36c-454a10f4',
            'returnEmpName': '',
            'userId': 'abb5184d43ca-960c-b640-c36c-454a10f4',
            'workId': ''
        }
        auditRequest.audit(auditParams).then(() => {
            hideLoading()
            _this.clientPop('suc', '审核成功', _this.handleClose)
        }).catch(()=>{
            hideLoading()
        })
    }
}
//保存全部数据
function saveAll (vueObject, requestFn) {
    const _this = vueObject
    showLoading()
    _this.errorList = []
    Promise.all(requestFn())
        .then(() => {
            _this.$store.commit('contract/setMaterialList', [])
            hideLoading()
            _this.clientPop('suc', '保存成功')
        })
        .catch(err => {
            let errMsg = null
            if(  typeof err === 'string') {
                errMsg = err
            }else if(err instanceof Array) {
                errMsg = err.join('，')
            }else if(err instanceof Object) {
                if(err.code) {
                    errMsg = Object.values(err.data)
                }else{
                    errMsg = err
                }
            }
            _this.clientPop('errDt', errMsg, ()=>{
                _this.scorllError()
            }, null, null, '保存失败')
        })
        .finally(() => {
            hideLoading()
        })
}
//保存并提交
function submitCommit (vueObject, requestFn) {
    const _this = vueObject
    showLoading()
    _this.errorList = []
    Promise.all(requestFn())
        .then(() => {
            _this.$store.commit('contract/setMaterialList', [])
            auditRequest.commitAudit(_this.auditParams).then(()=>{
                hideLoading()
                _this.clientPop('suc', '提交成功', _this.handleClose)
            })
        })
        .catch(err => {
            let errMsg = null
            if(  typeof err === 'string') {
                errMsg = err
            }else if(err instanceof Array) {
                errMsg = err.join('，')
            }else if(err instanceof Object) {
                if(err.code) {
                    errMsg = Object.values(err.data)
                }else{
                    errMsg = err
                }
            }
            _this.clientPop('errDt', errMsg, ()=>{
                _this.scorllError()
            }, null, null, '提交失败')
        })
        .finally(() => {
            hideLoading()
        })
}
//切换本位币汇率
function handleCurrency (val, vueObject) {
    const _this = vueObject
    _this.formData.currencyName = _this.currencyForm.find(x=>x.value === val).label
    if(_this.formData.currencyName === '人民币') {
        _this.formData.rmbRate = 1
    }else{
        showLoading()
        getRmbRate({
            currency: val,
            orgId: _this.userInfo.orgInfo.orgId
        }).then(res=>{
            _this.formData.rmbRate = res.rate
        }).catch(()=>{
            _this.formData.rmbRate = 0
        }).finally(()=>{
            hideLoading ()
        })
    }
    if(_this.formData.currencyId === _this.formData.baseCurId) {
        _this.formData.baseCurRate = 1
        _this.showBaseCurName = false
    }else{
        _this.showBaseCurName = true
    }}
//查看详情页
function showContract (path, billid) {
    openAppClient(`/${ path }?billid=${billid}&isview=true`, '查看合同')
}
//查看招标详情页
function showBinding (path, billid) {
    console.log(`/${ path }?billid=${billid}&isview=true`)
    openAppClient(`/${ path }?billid=${billid}&isview=true`, '查看招标')
}
//跳转到详情页结算台账栏
function showSettlementList (billid, path, vueObject) {
    const _this = vueObject
    _this.$router.push({
        path,
        query: {
            billid,
            name: 'settlementParameter'
        }
    })}
//根据合同状态跳转页面
function showPage (row, pageJson, vueObject, jump = true) {
    const _this = vueObject
    const billInfo = {}
    const goPage = (billid, pages, state) => {
        if(!billid) return
        const { editPage, showPage, billType } = pages
        billInfo.billId = billid
        billInfo.state = state
        billInfo.billType = billType
        if(jump) {
            const auditParams = {
                'billId': billid,
                'billType': billType
            }
            if(state === -1 || state === 2 || state === 5 || !_this.permission(['edit'])) {
                _this.$router.push({
                    path: showPage,
                    query: { billid }
                })
            }else{
                auditRequest.getUnitInfoByBillId(auditParams).then(res => {
                    if(res.canModify) {
                        _this.$router.push({
                            path: editPage,
                            query: { billid }
                        })
                    }else{
                        _this.$router.push({
                            path: showPage,
                            query: { billid }
                        })
                    }
                })
            }
        }

    }
    try{
        const { apply, sign, changeApply, changeSign, stop } = pageJson
        const { contractState, billId, state, contractSignState, contractChangeApplyState, contractChangeSignState, contractStopState } = row
        if(contractState === 0 || contractState === 1 || contractState === 2 || contractState === 10 || contractState === 11 || contractState === 12) {
            goPage(billId, apply, state)
        }
        else if(contractState === 3 || contractState === 4 ) {
            goPage(contractSignState.billId, sign, contractSignState.state)
        }else if(contractState === 5 || contractState === 6) {
            goPage(contractChangeApplyState.billId, changeApply, contractChangeApplyState.state)
        }else if(contractState === 7) {
            goPage(contractChangeSignState.billId, changeSign, contractChangeSignState.state)
        }else if(contractState === 8 || contractState === 9) {
            goPage(contractStopState.billId, stop, contractStopState.state)
        }
        if(!jump) return billInfo
    }
    catch(err) {
        return {}
    }

}
export {
    exas,
    handleCurrency,
    showContract,
    showBinding,
    saveAll,
    submitCommit,
    showSettlementList,
    showPage
}